use reqwest;

use crate::runtime::runtime;

/// 检查远程文件是否存在
pub fn check_remote_file_exists(url: reqwest::Url) -> runtime::result::InternalErrorResult<bool> {
    let response = reqwest::blocking::get(url).map_err(|e| runtime::error::InternalError::new(format!("Could not check remote file: {}", e.to_string())))?;

    match response.status() {
        reqwest::StatusCode::OK => Ok(true),
        reqwest::StatusCode::NOT_FOUND => Ok(false),
        _ => Err(runtime::error::InternalError::new(format!("Could not check remote file: HTTP status: {}", response.status())))
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_check_remote_file_exists() {
        let url = reqwest::Url::parse("https://gitee.com/Luna-CY/hui-hui/releases/download/v0.3.1/hui-hui_linux_aarch64_v0.3.1.tar.gz");
        assert_eq!(true, url.is_ok());

        let result = super::check_remote_file_exists(url.unwrap());
        assert_eq!(true, result.is_ok(), "P1 检查远程文件失败: {}", result.unwrap_err());
        assert_eq!(true, result.unwrap());

        let url = reqwest::Url::parse("https://gitee.com/Luna-CY/hui-hui/releases/download/v0.3.1/hui-hui_linux_aarch64_v0.3.1-not-exists.tar.gz");
        assert_eq!(true, url.is_ok());

        let result = super::check_remote_file_exists(url.unwrap());
        assert_eq!(true, result.is_ok(), "P2 检查远程文件失败: {}", result.unwrap_err());
        assert_eq!(false, result.unwrap());
    }
}